package effectivejava.chapter3.item13;
import java.util.Arrays;
import java.util.EmptyStackException;
/**
 * @author baicaixiaozhan
 * @since 2020/9/16
 */
public class CloneConventionDemo {

    public static void main(String[] args) throws CloneNotSupportedException {
        convention();
    }

    /**
     * 当类没有 final 修饰时, 就不能轻易将 clone 方法, 通过构造器来实现.
     * 否者, 可能会影响到子类中 {@code super.clone()} 返回类 类型. 如
     * {@link CloneConventionDemo#convention()} 中 ① 所示
     * <p />
     *
     * {@code x.clone().getClass() == x.getClass()}
     */
    public static void convention() throws CloneNotSupportedException {
        final BasePro basePro = new BasePro();
        // 此时的 clone 为 BasePro 的父类 Base
        // ①
        // class CloneConventionDemo$Base
        // ②
        // class CloneConventionDemo$BasePro
        System.out.println("basePro.clone().getClass() : " + basePro.clone().getClass());

        // class CloneConventionDemo$BasePro
        System.out.println("basePro.getClass() : " + basePro.getClass());
    }

    /**
     * 如果不是调用 {@link Object#clone()}, 就无需实现 {@link Cloneable} 接口
     */
    public static class Base {
        @Override
        public Object clone() throws CloneNotSupportedException {
            // ①
            return new Base();
            // ②
            // return super.clone();
        }
    }

    public static class BasePro extends Base implements Cloneable {
        @Override
        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }

}

